<template>
  <div class="analysis-overview">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>数据分析总览</h2>
        <p>全面了解用户画像、行为特征和消费模式</p>
      </div>
      <div class="header-actions">
        <el-button :icon="Refresh" @click="refreshAllData" :loading="loading">
          刷新数据
        </el-button>
        <el-button :icon="Download" @click="exportReport">
          导出报告
        </el-button>
      </div>
    </div>

    <!-- 核心指标概览 -->
    <div class="metrics-overview" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="6" v-for="metric in coreMetrics" :key="metric.key">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon">
                <el-icon :size="28" :color="metric.color">
                  <component :is="metric.icon" />
                </el-icon>
              </div>
              <div class="metric-info">
                <h3>{{ metric.title }}</h3>
                <p class="metric-value">{{ metric.value }}</p>
                <span class="metric-desc">{{ metric.description }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分析模块快捷入口 -->
    <div class="analysis-modules">
      <el-row :gutter="20">
        <el-col :span="6" v-for="module in analysisModules" :key="module.key">
          <el-card class="module-card" @click="navigateToModule(module.path)">
            <div class="module-content">
              <div class="module-icon">
                <el-icon :size="32" :color="module.color">
                  <component :is="module.icon" />
                </el-icon>
              </div>
              <div class="module-info">
                <h3>{{ module.title }}</h3>
                <p>{{ module.description }}</p>
                <div class="module-stats" v-if="module.stats">
                  <span v-for="stat in module.stats" :key="stat.label" class="stat-item">
                    {{ stat.label }}: {{ stat.value }}
                  </span>
                </div>
              </div>
              <div class="module-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快速洞察 -->
    <div class="quick-insights" v-loading="loading">
      <el-card>
        <template #header>
          <div class="card-header">
            <h3>快速洞察</h3>
            <span class="update-time">更新时间: {{ updateTime }}</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="insight-item">
              <h4>用户画像特征</h4>
              <ul>
                <li v-for="insight in userProfileInsights" :key="insight">{{ insight }}</li>
              </ul>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="insight-item">
              <h4>行为模式分析</h4>
              <ul>
                <li v-for="insight in behaviorInsights" :key="insight">{{ insight }}</li>
              </ul>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="insight-item">
              <h4>消费趋势洞察</h4>
              <ul>
                <li v-for="insight in consumptionInsights" :key="insight">{{ insight }}</li>
              </ul>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Refresh, Download, ArrowRight, User, TrendCharts, 
  ShoppingCart, DataBoard, Star, View, Monitor
} from '@element-plus/icons-vue'
import { 
  getBasicProfileAnalysis,
  getBehaviorProfileAnalysis,
  getConsumptionProfileAnalysis,
  getUserSegmentationAnalysis
} from '@/api/analysis'

const router = useRouter()

// 状态管理
const loading = ref(false)
const updateTime = ref('')

// 分析数据
const basicData = ref(null)
const behaviorData = ref(null)
const consumptionData = ref(null)
const segmentationData = ref(null)

// 核心指标
const coreMetrics = computed(() => [
  {
    key: 'total_users',
    title: '总用户数',
    value: basicData.value?.total_users?.toLocaleString() || '0',
    description: '活跃用户总数',
    icon: 'User',
    color: '#409EFF'
  },
  {
    key: 'avg_spending',
    title: '平均消费',
    value: consumptionData.value ? `¥${consumptionData.value.summary.avg_spending.toLocaleString()}` : '¥0',
    description: '用户平均消费金额',
    icon: 'ShoppingCart',
    color: '#67C23A'
  },
  {
    key: 'total_segments',
    title: '客户分群',
    value: segmentationData.value?.summary.total_segments || '0',
    description: '识别的客户分群数',
    icon: 'DataBoard',
    color: '#E6A23C'
  },
  {
    key: 'avg_activity',
    title: '平均活跃度',
    value: behaviorData.value ? `${behaviorData.value.summary.avg_last_login}天` : '0天',
    description: '平均登录间隔',
    icon: 'TrendCharts',
    color: '#F56C6C'
  }
])

// 分析模块
const analysisModules = ref([
  {
    key: 'basic_profile',
    title: '基础画像',
    description: '用户年龄、性别、地区、收入分布分析',
    path: '/analysis/profile/basic',
    icon: 'User',
    color: '#409EFF',
    stats: []
  },
  {
    key: 'behavior_profile',
    title: '行为画像',
    description: '用户活跃度、登录频率、网站参与度分析',
    path: '/analysis/profile/behavior',
    icon: 'Monitor',
    color: '#67C23A',
    stats: []
  },
  {
    key: 'consumption_profile',
    title: '消费画像',
    description: '消费金额、购买频率、品类偏好分析',
    path: '/analysis/profile/consumption',
    icon: 'ShoppingCart',
    color: '#E6A23C',
    stats: []
  },
  {
    key: 'user_segmentation',
    title: '用户分群',
    description: '基于RFM模型的客户价值分群分析',
    path: '/analysis/segmentation',
    icon: 'DataBoard',
    color: '#F56C6C',
    stats: []
  }
])

// 快速洞察
const userProfileInsights = computed(() => {
  if (!basicData.value) return ['数据加载中...']
  
  const insights = []
  const avgAge = basicData.value.summary.avg_age
  const avgIncome = basicData.value.summary.avg_income
  
  if (avgAge > 0) {
    insights.push(`用户平均年龄${avgAge}岁，主要为${avgAge < 30 ? '年轻' : avgAge < 45 ? '中年' : '成熟'}用户群体`)
  }
  
  if (avgIncome > 0) {
    const incomeLevel = avgIncome < 50000 ? '中低收入' : avgIncome < 100000 ? '中等收入' : '高收入'
    insights.push(`用户平均年收入${(avgIncome/10000).toFixed(1)}万，属于${incomeLevel}群体`)
  }
  
  if (basicData.value.gender_distribution.length > 0) {
    const maleCount = basicData.value.gender_distribution.find(item => item.label === '男性')?.value || 0
    const femaleCount = basicData.value.gender_distribution.find(item => item.label === '女性')?.value || 0
    const total = maleCount + femaleCount
    if (total > 0) {
      const maleRatio = ((maleCount / total) * 100).toFixed(1)
      insights.push(`用户性别分布：男性${maleRatio}%，女性${(100-maleRatio).toFixed(1)}%`)
    }
  }
  
  return insights.length > 0 ? insights : ['暂无数据']
})

const behaviorInsights = computed(() => {
  if (!behaviorData.value) return ['数据加载中...']
  
  const insights = []
  const avgTimeOnSite = behaviorData.value.summary.avg_time_on_site
  const avgPagesViewed = behaviorData.value.summary.avg_pages_viewed
  const avgLastLogin = behaviorData.value.summary.avg_last_login
  
  if (avgTimeOnSite > 0) {
    const engagement = avgTimeOnSite > 60 ? '高' : avgTimeOnSite > 30 ? '中' : '低'
    insights.push(`用户平均停留时间${avgTimeOnSite}分钟，参与度${engagement}`)
  }
  
  if (avgPagesViewed > 0) {
    insights.push(`用户平均浏览${avgPagesViewed}个页面`)
  }
  
  if (avgLastLogin > 0) {
    const activity = avgLastLogin <= 7 ? '高活跃' : avgLastLogin <= 30 ? '中活跃' : '低活跃'
    insights.push(`用户平均${avgLastLogin}天登录一次，整体${activity}`)
  }
  
  return insights.length > 0 ? insights : ['暂无数据']
})

const consumptionInsights = computed(() => {
  if (!consumptionData.value) return ['数据加载中...']
  
  const insights = []
  const avgSpending = consumptionData.value.summary.avg_spending
  const avgFrequency = consumptionData.value.summary.avg_frequency
  const avgOrderValue = consumptionData.value.summary.avg_order_value
  
  if (avgSpending > 0) {
    const spendingLevel = avgSpending > 5000 ? '高消费' : avgSpending > 2000 ? '中等消费' : '低消费'
    insights.push(`用户平均消费¥${avgSpending.toLocaleString()}，属于${spendingLevel}群体`)
  }
  
  if (avgFrequency > 0) {
    const frequencyLevel = avgFrequency > 12 ? '高频' : avgFrequency > 6 ? '中频' : '低频'
    insights.push(`用户年均购买${avgFrequency}次，${frequencyLevel}购买`)
  }
  
  if (avgOrderValue > 0) {
    insights.push(`用户平均订单价值¥${avgOrderValue.toLocaleString()}`)
  }
  
  return insights.length > 0 ? insights : ['暂无数据']
})

// 方法
const loadAllData = async () => {
  try {
    loading.value = true
    
    const [basicResponse, behaviorResponse, consumptionResponse, segmentationResponse] = await Promise.all([
      getBasicProfileAnalysis(),
      getBehaviorProfileAnalysis(),
      getConsumptionProfileAnalysis(),
      getUserSegmentationAnalysis()
    ])
    
    if (basicResponse.success) basicData.value = basicResponse.data
    if (behaviorResponse.success) behaviorData.value = behaviorResponse.data
    if (consumptionResponse.success) consumptionData.value = consumptionResponse.data
    if (segmentationResponse.success) segmentationData.value = segmentationResponse.data
    
    updateTime.value = new Date().toLocaleString()
    
  } catch (error) {
    console.error('加载分析数据失败:', error)
    ElMessage.error('加载分析数据失败')
  } finally {
    loading.value = false
  }
}

const refreshAllData = async () => {
  await loadAllData()
  ElMessage.success('数据已刷新')
}

const exportReport = () => {
  ElMessage.info('导出功能开发中...')
}

const navigateToModule = (path) => {
  router.push(path)
}

// 生命周期
onMounted(() => {
  loadAllData()
})
</script>

<style scoped>
.analysis-overview {
  padding: 0;
  background-color: transparent;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.metrics-overview {
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  cursor: default;
}

.metric-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.metric-info h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.metric-value {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.metric-desc {
  font-size: 12px;
  color: #999;
}

.analysis-modules {
  margin-bottom: 24px;
}

.module-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.module-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.module-content {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
}

.module-info {
  flex: 1;
}

.module-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.module-info p {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.module-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.stat-item {
  font-size: 11px;
  color: #999;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.module-arrow {
  color: #ccc;
}

.quick-insights .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.update-time {
  font-size: 12px;
  color: #999;
}

.insight-item h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
}

.insight-item ul {
  margin: 0;
  padding-left: 16px;
  list-style: none;
}

.insight-item li {
  margin-bottom: 8px;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  position: relative;
}

.insight-item li:before {
  content: '•';
  color: #409EFF;
  font-weight: bold;
  position: absolute;
  left: -12px;
}
</style>
